﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

/// <summary>
/// 表达式树块代码块应用
/// </summary>
/// <remarks>
/// 目的
/// 使用代码构造一个表达式树代码块.
/// 
/// 
/// </remarks>
public partial class ExpressionTree表达式树_表达式树块 : System.Web.UI.Page
{


    protected void Page_Load(object sender, EventArgs e)
    {

        Expression<Func<int, string, string>> dxpr = (int m, string abc) => m + abc;

        LambdaExpression x = null;
        Action a = () =>
        {
            x = 表达式树代码块();
        };
        Action b = () =>
        {
            x.Compile();
        };
        
        Response.Write(string.Format("产生表达式用时:{0},{1}<br/>", a.StopwatchRun(), x));
        Response.Write(string.Format("编译表达式用时:{0},{1}<br/>", b.StopwatchRun(), x));
        Action c = () => { string ax = null; ax.ToArray(); };
        //aaa(c);
    }

    public void aaa(Action act)
    {
        try { act(); }
        catch
        {
            throw;
        }
        finally {
            int a = 0;
        }
    }


    public LambdaExpression 表达式树代码块()
    {
        ParameterExpression a = BlockExpression.Parameter(typeof(int), "a");
        ConstantExpression b = BlockExpression.Constant(1);
        //c=a+b
        BinaryExpression c = BlockExpression.Add(a, b);

        //调用string.Concat()
        var method = typeof(string).GetMethods().Where(p => p.Name == "Concat").ElementAt(1);

        var guid = typeof(Guid).GetMethod("NewGuid");
        var guidtostring = typeof(Guid).GetMethods().Where(p => p.Name == "ToString").ElementAt(0);
        var guida = Expression.Call(null, guid);
        var guidstr = Expression.Call(guida, guidtostring);


        var inttostring = Expression.Call(c, typeof(int).GetMethods().Where(p => p.Name == "ToString").ElementAt(0));
        var ifthen = Expression.Condition(Expression.GreaterThanOrEqual(a, b), inttostring, Expression.Constant("sfsdfsdfsd"));
        var join = Expression.Call(method, ifthen, guidstr);

        Expression<Func<int, string>> expr = BlockExpression.Lambda<Func<int, string>>(join, a);

        //动态表达式2
        LambdaExpression exprx = Expression.Lambda(join, a);
        //产生委托类型 System.Func<int,string>
        dynamic abc = exprx.Compile();
        
        return expr;
    }

    public string 需要构造的方法(int a)
    {
        int b = 1;
        int c = a + b;
        return c + Guid.NewGuid().ToString();
    }
}



public partial class ExpressionTree表达式树_表达式树块 {

    public void NNabc() { }
}